package com.ruoyi.flowable.controller;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.flowable.domain.vo.FlowTaskVo;
import com.ruoyi.flowable.mapper.ActRejectRecordMapper;
import com.ruoyi.flowable.mapper.WorkOrderAssetRelMapper;
import com.ruoyi.flowable.service.IFlowInstanceService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>工作流流程实例管理<p>
 *
 * @author Tony
 * @date 2021-04-03
 */
@Slf4j
@RestController
@RequestMapping("/flowable/instance")
public class FlowInstanceController extends BaseController {

    @Autowired
    private IFlowInstanceService flowInstanceService;
    @Resource
    private WorkOrderAssetRelMapper workOrderAssetRelMapper;
    @Resource
    private ActRejectRecordMapper rejectRecordMapper;

    /**
     * 根据流程定义id启动流程实例
     * @param procDefId 流程定义id
     * @param variables 变量集合,json对象
     * @return
     */
    @PostMapping("/startBy/{procDefId}")
    public AjaxResult startById(@PathVariable(value = "procDefId") String procDefId,
                                @RequestBody Map<String, Object> variables) {
        return flowInstanceService.startProcessInstanceById(procDefId, variables);

    }

    /**
     * 激活或挂起流程实例
     * @param state 1:激活,2:挂起
     * @param instanceId 流程实例ID
     * @return
     */
    @PostMapping(value = "/updateState")
    public AjaxResult updateState(@RequestParam("state") Integer state,
                                  @RequestParam("instanceId") String instanceId) {
        flowInstanceService.updateState(state, instanceId);
        return AjaxResult.success();
    }

    //结束流程实例
    @PostMapping(value = "/stopProcessInstance")
    public AjaxResult stopProcessInstance(@RequestBody FlowTaskVo flowTaskVo) {
        flowInstanceService.stopProcessInstance(flowTaskVo);
        return AjaxResult.success();
    }

    /**
     * 删除流程实例
     * @param instanceIds 流程实例ID
     * @param deleteReason 删除原因
     * @return
     */
    @Log(title = "删除任务", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/delete/{instanceIds}")
    public AjaxResult delete(@PathVariable("instanceIds") String[] instanceIds,
                             @RequestParam(value = "deleteReason", required = false) String deleteReason) {
        //删除流程实例-资产工单
        workOrderAssetRelMapper.deleteByProcInsIds(instanceIds);
        //删除驳回记录中的内容
        rejectRecordMapper.deleteByProcInstIds(instanceIds);

        for (String instanceId : instanceIds) {
            flowInstanceService.delete(instanceId, deleteReason);
        }
        return AjaxResult.success();
    }
}
